package com.shop.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author WuLiangHang
 */
//http://localhost:8083/shop/pages/manager/manager.jsp
@WebFilter(urlPatterns = "*.txt")
public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * doFilter方法 专门用于拦截请求。可以做权限检查
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //如果用户未登陆，不允许访问到pages/manager文件夹下的所有内容
        //1.获取用户是否登录的状态 从Session中提取出"user"的对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (user == null) {
            //2.检查 2_1如果是null说明没有登录进行重定向回首页
            response.sendRedirect(request.getContextPath() + "/index.jsp");
            System.out.println("未登录，禁止访问manager目录");
        } else {
            //2_2 如果已经登录 让程序继续往下访问用户的目标资源
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
